<!--
 * @Author: zhangfeng
 * @Date: 2023-12-27 15:54:18
 * @LastEditTime: 2023-12-27 16:56:41
 * @LastEditors: zhangfeng
 * @Description: 
 * @FilePath: \manager\managersystem\src\views\role\module\RoleDialog.vue
 * © 2023 张峰，All rights reserved.
-->
<template>
	<el-dialog v-model="dialogVisible" :title="tips" width="30%">
		<el-form
			ref="ruleFormRef"
			:model="ruleForm"
			:rules="rules"
			label-width="120px"
			class="demo-ruleForm"
			:size="formSize"
			status-icon
		>
			<el-form-item label="角色名称" prop="name">
				<el-input v-model="ruleForm.name" />
			</el-form-item>
			<el-form-item label="描述" prop="description">
				<el-input v-model="ruleForm.description" />
			</el-form-item>
		</el-form>
		<template #footer>
			<span class="dialog-footer">
				<el-form-item>
					<el-button type="primary" @click="submitForm(ruleFormRef)">
						{{ submitText }}
					</el-button>
					<el-button @click="dialogVisible = false">Cancal</el-button>
				</el-form-item>
			</span>
		</template>
	</el-dialog>
</template>

<script setup lang="ts">
import type { FormInstance, FormRules } from 'element-plus';
import { useRoles } from '../../../composables/useRoles';
import { globalInjectSymbol } from '../../../utils/symbolKey';

const { successOrError } = inject(globalInjectSymbol) || {};
const tips = ref('');
const dialogVisible = ref(false);
const ruleForm = ref();
const { createRoles, updateRoles } = useRoles();
const emit = defineEmits<{ (e: 'getlist'): void }>();
const rules = ref<FormRules>({
	name: [{ required: true, message: '请输入角色名称', trigger: 'blur' }],
});
const formSize = ref<'default' | 'small' | 'large'>('default');
const submitText = ref('create');
const ruleFormRef = ref<FormInstance>();
const resetRuleFrom = ref({
	name: '',
	description: '',
});
const submitForm = async (refs: FormInstance | undefined) => {
	if (!refs) return;
	await refs.validate(async (valid, fields) => {
		if (valid) {
			let result: AxiosResponse<ResponseData>;
			if (ruleForm.value.id) {
				result = await updateRoles(ruleForm.value);
			} else {
				result = await createRoles(ruleForm.value);
			}
			if (successOrError) {
				successOrError(result);
				dialogVisible.value = false;
			}
			emit('getlist');
		}
	});
};
const addRoles = () => {
	dialogVisible.value = true;
	ruleForm.value = resetRuleFrom.value;
	submitText.value = 'create';
};

const editRoles = (row: RoleTableData[]) => {
	dialogVisible.value = true;
	ruleForm.value = row;
	submitText.value = 'update';
};

defineExpose({
	addRoles,
	editRoles,
});
</script>

<style scoped></style>
